package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.DishFlavor;
import com.itheima.reggie.pojo.Setmeal;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {

    @Autowired
    private DishService service;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/page")
    public R<Page> pag(int page,int pageSize,String name){

        Page<Dish> dishPage=new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage=new Page<>();
        LambdaQueryWrapper<Dish> lqw=new LambdaQueryWrapper<>();
        lqw.like(name!=null,Dish::getName,name);
        lqw.orderByAsc(Dish::getSort);
        service.page(dishPage,lqw);
        BeanUtils.copyProperties(dishPage,dishDtoPage,"records");

        List<Dish> records = dishPage.getRecords();

        List<DishDto> dtos =records.stream().map((item)->{
            DishDto dto=new DishDto();
            BeanUtils.copyProperties(item,dto);
            Long categoryId = item.getCategoryId();
            if (categoryId!=null){
                Category category = categoryService.getById(categoryId);
                String categoryname = category.getName();
                dto.setCategoryName(categoryname);
            }
            return dto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(dtos);

        return R.success(dishDtoPage);
    }

    @PostMapping
    public R<String> add(@RequestBody DishDto dishDto){

        service.saveWithFlavor(dishDto);
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);

        return R.success("恭喜你,添加成功咯!");
    }
    @GetMapping("/{id}")
    public R<DishDto> getWithFlavor(@PathVariable Long id){

        DishDto dishDto = service.getWithFlavor(id);

        return R.success(dishDto);
    }
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){

        log.info(dishDto.toString());
        service.updateWithFlavor(dishDto);
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);

        return R.success("修改成功啦!");
    }
    @GetMapping("/list")
    public R<List<DishDto>> listR(Dish dish){

        List<DishDto> dtos=null;
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        dtos = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dtos!=null){
            return R.success(dtos);
        }

        LambdaQueryWrapper<Dish> lqw=new LambdaQueryWrapper();
        lqw.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        lqw.eq(Dish::getStatus,1);
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> dishes = service.list(lqw);

        dtos=dishes.stream().map((item)->{
            DishDto dishDto=new DishDto();
            BeanUtils.copyProperties(item,dishDto);

            Long categoryId = item.getCategoryId();
            Category dishbyId = categoryService.getById(categoryId);
            if (categoryId!=null){
                String name = dishbyId.getName();
                dishDto.setCategoryName(name);
            }
            Long id = item.getId();
            LambdaQueryWrapper<DishFlavor> lq=new LambdaQueryWrapper<>();
            lq.eq(DishFlavor::getDishId,id);
            List<DishFlavor> list = dishFlavorService.list(lq);
            dishDto.setFlavors(list);
            return dishDto;
        }).collect(Collectors.toList());

        redisTemplate.opsForValue().set(key,dtos,60, TimeUnit.MINUTES);

        return R.success(dtos);
    }



    @DeleteMapping
    public R<String> deleteR(@RequestParam List<Long> ids){

        service.removeByIds(ids);

        return R.success("删除成功0");
    }

    /*@PostMapping("/status/{status}")
    public R<String> idsAndstatus(@PathVariable int status,@RequestParam Long ids){

        LambdaQueryWrapper<Dish> lqw=new LambdaQueryWrapper<>();
        lqw.eq(Dish::getId,ids);
        List<Dish> list = service.list(lqw);
        List<Dish> dishs=list.stream().map((item)->{
            item.setStatus(status);
            return item;
        }).collect(Collectors.toList());
        log.info("{}",dishs);
        service.updateBatchById(dishs);
        return R.success("禁用");
    }*/

    @PostMapping("/status/{status}")
    public R<String> idsAndstatus(@PathVariable int status,@RequestParam List<Long> ids){
        ids.forEach((item)->{
            System.out.println(item);
            LambdaQueryWrapper<Dish> lqw=new LambdaQueryWrapper();
            lqw.eq(Dish::getId,item);
            Dish one = service.getOne(lqw);
            one.setStatus(status);
            service.updateById(one);
        });
        return R.success("成功");
    }

}
